package com.meiyu.live.tv.widget;

import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.RequestCallbackWrapper;
import com.netease.nimlib.sdk.chatroom.ChatRoomService;
import com.netease.nimlib.sdk.chatroom.constant.MemberQueryType;
import com.netease.nimlib.sdk.chatroom.constant.MemberType;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomMember;
import com.netease.nimlib.sdk.chatroom.model.MemberOption;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.meiyu.live.BaseActivity;
import com.meiyu.live.R;
import com.meiyu.live.net.param.GetInfosParams;
import com.meiyu.live.net.response.GetInfosResponse;
import com.meiyu.live.util.DisplayUtils;
import com.meiyu.live.util.ToastUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zbl on 2016/12/12.
 * 房间管理列表dialog
 */
public class RoomManageListPopwindow extends PopupWindow implements View.OnClickListener {

    public interface RoomManageListener {
        void onRemoveMute();
    }

    private Context context;
    private LayoutInflater inflater;
    private ImageLoader imageLoader;
    private DisplayImageOptions options;

    private RoomManageListener listener;

    private View rootView;
    private View btn_manage, btn_mute;
    private View view_gap, layout_btn_manage;
    private ImageView iv_underline0, iv_underline1;
    private ListView listView_manage, listView_mute;
    private ManageAdapter manageAdapter;
    private MuteAdapter muteAdapter;

    private long room_id;
    private ArrayList<ChatRoomMember> manageMemberList = new ArrayList<>();
    private ArrayList<ChatRoomMember> muteMemberList = new ArrayList<>();

    public RoomManageListPopwindow(Context context) {
        super(context);
        init(context);
    }

    private void init(Context context) {
        this.context = context;
        inflater = LayoutInflater.from(context);
        imageLoader = ImageLoader.getInstance();
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.icon_def_header)          // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.drawable.icon_def_header)  // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.icon_def_header)       // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory(true)                        // 设置下载的图片是否缓存在内存中
                .cacheOnDisk(true)                          // 设置下载的图片是否缓存在SD卡中
                .build();
        rootView = inflater.inflate(R.layout.dialog_room_manage_list, null);
        setContentView(rootView);
        setWidth(DisplayUtils.dpToPixel(context.getApplicationContext(), 180));
        setHeight(DisplayUtils.dpToPixel(context.getApplicationContext(), 240));
        setBackgroundDrawable(context.getResources().getDrawable(R.drawable.background_dialog_transblack));
        setOutsideTouchable(true);

        btn_manage = rootView.findViewById(R.id.btn_manage);
        btn_manage.setOnClickListener(this);
        btn_mute = rootView.findViewById(R.id.btn_mute);
        btn_mute.setOnClickListener(this);
        view_gap = rootView.findViewById(R.id.view_gap);
        layout_btn_manage = rootView.findViewById(R.id.layout_btn_manage);
        iv_underline0 = (ImageView) rootView.findViewById(R.id.iv_underline0);
        iv_underline1 = (ImageView) rootView.findViewById(R.id.iv_underline1);
        listView_manage = (ListView) rootView.findViewById(R.id.listview_manage);
        listView_mute = (ListView) rootView.findViewById(R.id.listview_mute);
        manageAdapter = new ManageAdapter();
        listView_manage.setAdapter(manageAdapter);
        muteAdapter = new MuteAdapter();
        listView_mute.setAdapter(muteAdapter);
        setState(0);
    }

    @Override
    public void onClick(View view) {
        if (view == btn_manage) {
            setState(0);
        } else if (view == btn_mute) {
            setState(1);
        }
    }

    /**
     * 0场控，1禁言
     *
     * @param state
     */
    private void setState(int state) {
        if (state == 0) {
            listView_manage.setVisibility(View.VISIBLE);
            listView_mute.setVisibility(View.GONE);
            iv_underline0.setVisibility(View.INVISIBLE);
            iv_underline1.setVisibility(View.VISIBLE);
        } else {
            listView_manage.setVisibility(View.GONE);
            listView_mute.setVisibility(View.VISIBLE);
            iv_underline1.setVisibility(View.INVISIBLE);
            iv_underline0.setVisibility(View.VISIBLE);
        }
    }

    public void setListener(RoomManageListener listener) {
        this.listener = listener;
    }

    public void setIsAnchor(boolean isAnchor) {
        if (isAnchor) {
            layout_btn_manage.setVisibility(View.VISIBLE);
            view_gap.setVisibility(View.VISIBLE);
        } else {
            layout_btn_manage.setVisibility(View.GONE);
            view_gap.setVisibility(View.GONE);
            setState(1);
        }
    }

    private int dataRequestCount = 0;
    private HashMap<String, ChatRoomMember> needRequestInfoMemberMap = new HashMap<>();

    public void updateData(long room_id) {
        this.room_id = room_id;
        dataRequestCount = 0;
        needRequestInfoMemberMap.clear();
        NIMClient.getService(ChatRoomService.class)
                .fetchRoomMembers(room_id + "", MemberQueryType.GUEST, 0, Integer.MAX_VALUE)
                .setCallback(new RequestCallback<List<ChatRoomMember>>() {
                    @Override
                    public void onSuccess(List<ChatRoomMember> param) {
                        if (param != null) {
                            manageMemberList.clear();
                            muteMemberList.clear();
                            for (ChatRoomMember member : param) {
                                if (member.isMuted()) {
                                    parseRobotData(member);
                                    muteMemberList.add(member);
                                    checkUserInfo(member);
                                } else if (member.getMemberType() == MemberType.ADMIN) {
                                    parseRobotData(member);
                                    manageMemberList.add(member);
                                    checkUserInfo(member);
                                }
                            }
                            manageAdapter.notifyDataSetChanged();
                        }
                        dataRequestCount += 1;
                        if (dataRequestCount == 2) {
                            getUserInfos();
                        }
                    }

                    @Override
                    public void onFailed(int code) {
                        dataRequestCount += 1;
                        if (dataRequestCount == 2) {
                            getUserInfos();
                        }
                    }

                    @Override
                    public void onException(Throwable exception) {
                        dataRequestCount += 1;
                        if (dataRequestCount == 2) {
                            getUserInfos();
                        }
                    }
                });

        NIMClient.getService(ChatRoomService.class)
                .fetchRoomMembers(room_id + "", MemberQueryType.NORMAL, 0, Integer.MAX_VALUE)
                .setCallback(new RequestCallback<List<ChatRoomMember>>() {
                    @Override
                    public void onSuccess(List<ChatRoomMember> param) {
                        if (param != null) {
                            manageMemberList.clear();
                            muteMemberList.clear();
                            for (ChatRoomMember member : param) {
                                if (member.isMuted()) {
                                    parseRobotData(member);
                                    muteMemberList.add(member);
                                    checkUserInfo(member);
                                } else if (member.getMemberType() == MemberType.ADMIN) {
                                    parseRobotData(member);
                                    manageMemberList.add(member);
                                    checkUserInfo(member);
                                }
                            }
                            manageAdapter.notifyDataSetChanged();
                        }
                        dataRequestCount += 1;
                        if (dataRequestCount == 2) {
                            getUserInfos();
                        }
                    }

                    @Override
                    public void onFailed(int code) {
                        dataRequestCount += 1;
                        if (dataRequestCount == 2) {
                            getUserInfos();
                        }
                    }

                    @Override
                    public void onException(Throwable exception) {
                        dataRequestCount += 1;
                        if (dataRequestCount == 2) {
                            getUserInfos();
                        }
                    }
                });
    }

    private void checkUserInfo(final ChatRoomMember member) {
        if (member.getExtension() == null) {
            needRequestInfoMemberMap.put(member.getAccount(), member);
        }
    }

    private void getUserInfos() {
        if (needRequestInfoMemberMap.size() > 0) {
            String[] net_ease_id_array = new String[needRequestInfoMemberMap.size()];
            needRequestInfoMemberMap.keySet().toArray(net_ease_id_array);
            ((BaseActivity) context).request(new GetInfosParams(net_ease_id_array), GetInfosResponse.class, new Response.Listener<GetInfosResponse>() {
                @Override
                public void onResponse(GetInfosResponse getInfosResponse) {
                    if (getInfosResponse != null && getInfosResponse.getRemark() != null) {
                        for (GetInfosResponse.UserInfo userInfo : getInfosResponse.getRemark()) {
                            ChatRoomMember member = needRequestInfoMemberMap.get(userInfo.getNet_ease());
                            if (member != null) {
                                Map<String, Object> extMap = new HashMap<>();
                                extMap.put("net_ease_id", userInfo.getNet_ease());
                                extMap.put("icon", userInfo.getAvatar());
                                extMap.put("nick", userInfo.getName());
                                //extMap.put("level", relationInfo.getLevel());
                                member.setExtension(extMap);
                            }
                        }
                        manageAdapter.notifyDataSetChanged();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {

                }
            });

        }
    }

    public void addManager(String neteaseId) {
        if (TextUtils.isEmpty(neteaseId)) {
            return;
        }
        ArrayList<String> accounts = new ArrayList<>();
        accounts.add(neteaseId);
        NIMClient.getService(ChatRoomService.class)
                .fetchRoomMembersByIds(room_id + "", accounts)
                .setCallback(new RequestCallbackWrapper<List<ChatRoomMember>>() {

                    @Override
                    public void onResult(int code, List<ChatRoomMember> result, Throwable exception) {
                        if (result != null && result.size() > 0) {
                            ChatRoomMember member = result.get(0);
                            removeManager(member.getAccount());
                            manageMemberList.add(0, member);
                            manageAdapter.notifyDataSetChanged();
                        }
                    }
                });
    }

    public void removeManager(String neteaseId) {
        if (TextUtils.isEmpty(neteaseId)) {
            return;
        }
        for (ChatRoomMember member : manageMemberList) {
            if (TextUtils.equals(member.getAccount(), neteaseId)) {
                manageMemberList.remove(member);
                manageAdapter.notifyDataSetChanged();
                break;
            }
        }
    }

    public void addMute(String neteaseId) {
        if (TextUtils.isEmpty(neteaseId)) {
            return;
        }
        ArrayList<String> accounts = new ArrayList<>();
        accounts.add(neteaseId);
        NIMClient.getService(ChatRoomService.class)
                .fetchRoomMembersByIds(room_id + "", accounts)
                .setCallback(new RequestCallbackWrapper<List<ChatRoomMember>>() {

                    @Override
                    public void onResult(int code, List<ChatRoomMember> result, Throwable exception) {
                        if (result != null && result.size() > 0) {
                            ChatRoomMember member = result.get(0);
                            removeManager(member.getAccount());
                            muteMemberList.add(0, member);
                            muteAdapter.notifyDataSetChanged();
                        }
                    }
                });
    }

    public void removeMute(String neteaseId) {
        if (TextUtils.isEmpty(neteaseId)) {
            return;
        }
        for (ChatRoomMember member : muteMemberList) {
            if (TextUtils.equals(member.getAccount(), neteaseId)) {
                muteMemberList.remove(member);
                muteAdapter.notifyDataSetChanged();
                break;
            }
        }
    }


    private HashMap<String, String> robotMap = new HashMap<>();

    private void parseRobotData(ChatRoomMember bean) {
        Map<String, Object> map = bean.getExtension();
        if (map != null) {
            String ext = (String) map.get("ext");
            if (!TextUtils.isEmpty(ext)) {
                if (robotMap.size() == 0) {//初始化map数据
                    try {
                        JSONArray jsonArray = new JSONArray(ext);
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject object = jsonArray.getJSONObject(i);
                            String netEaseId = object.optString("net_ease_id");
                            if (!TextUtils.isEmpty(netEaseId)) {
                                robotMap.put(netEaseId, object.toString());
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                String data = robotMap.get(bean.getAccount());
                if (!TextUtils.isEmpty(data)) {
                    try {
                        JSONObject object = new JSONObject(data);
                        Map<String, Object> extMap = new HashMap<>();
                        extMap.put("net_ease_id", object.opt("net_ease_id"));
                        extMap.put("icon", object.opt("icon"));
                        extMap.put("level", object.opt("level"));
                        extMap.put("nick", object.opt("nick"));
                        bean.setExtension(extMap);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    class ManageAdapter extends BaseAdapter {

        class MessageViewHolder {
            ImageView iv_avatar;
            TextView tv_name, btn_remove;
        }

        private View.OnClickListener onBtnClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int p = (int) v.getTag();
                final ChatRoomMember member = manageMemberList.get(p);
                //解除管理员身份
                NIMClient.getService(ChatRoomService.class)
                        .markChatRoomManager(false, new MemberOption(room_id + "", member.getAccount()))
                        .setCallback(new RequestCallback<ChatRoomMember>() {
                            @Override
                            public void onSuccess(ChatRoomMember param) {
                                manageMemberList.remove(member);
                                manageAdapter.notifyDataSetChanged();
                            }

                            @Override
                            public void onFailed(int code) {
                                ToastUtil.show("解除场控失败");
                            }

                            @Override
                            public void onException(Throwable exception) {
                                ToastUtil.show("解除场控发生错误");
                            }
                        });
            }
        };

        @Override
        public int getCount() {
            return manageMemberList.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup viewGroup) {
            MessageViewHolder holder;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.adapter_room_manager, null);
                holder = new MessageViewHolder();
                holder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
                holder.btn_remove = (TextView) convertView.findViewById(R.id.btn_remove);
                holder.btn_remove.setOnClickListener(onBtnClickListener);
                holder.iv_avatar = (ImageView) convertView.findViewById(R.id.iv_avatar);
                convertView.setTag(holder);
            } else {
                holder = (MessageViewHolder) convertView.getTag();
            }
            holder.btn_remove.setTag(position);
            ChatRoomMember member = manageMemberList.get(position);
            Map<String, Object> map = member.getExtension();
            if (map != null) {
                holder.tv_name.setText((String) map.get("nick"));
                imageLoader.displayImage((String) map.get("icon"), holder.iv_avatar, options);
            } else {
                holder.tv_name.setText(member.getNick());
                imageLoader.displayImage(member.getAvatar(), holder.iv_avatar, options);
            }
            return convertView;
        }
    }

    class MuteAdapter extends BaseAdapter {

        class MessageViewHolder {
            ImageView iv_avatar;
            TextView tv_name, btn_remove;
        }

        private View.OnClickListener onBtnClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int p = (int) v.getTag();
                final ChatRoomMember member = muteMemberList.get(p);
                MemberOption option = new MemberOption(room_id + "", member.getAccount());
                NIMClient.getService(ChatRoomService.class)
                        .markChatRoomMutedList(false, option)
                        .setCallback(new RequestCallback<ChatRoomMember>() {

                            @Override
                            public void onSuccess(ChatRoomMember param) {
                                muteMemberList.remove(member);
                                muteAdapter.notifyDataSetChanged();
                            }

                            @Override
                            public void onFailed(int code) {
                                ToastUtil.show("解除禁言失败");
                            }

                            @Override
                            public void onException(Throwable exception) {
                                ToastUtil.show("解除禁言发生错误");
                            }
                        });
            }
        };

        @Override
        public int getCount() {
            return muteMemberList.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup viewGroup) {
            MessageViewHolder holder;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.adapter_room_manager, null);
                holder = new MessageViewHolder();
                holder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
                holder.btn_remove = (TextView) convertView.findViewById(R.id.btn_remove);
                holder.btn_remove.setOnClickListener(onBtnClickListener);
                holder.iv_avatar = (ImageView) convertView.findViewById(R.id.iv_avatar);
                convertView.setTag(holder);
            } else {
                holder = (MessageViewHolder) convertView.getTag();
            }
            holder.btn_remove.setTag(position);
            ChatRoomMember member = muteMemberList.get(position);
            Map<String, Object> map = member.getExtension();
            if (map != null) {
                holder.tv_name.setText((String) map.get("nick"));
                imageLoader.displayImage((String) map.get("icon"), holder.iv_avatar, options);
            }
            return convertView;
        }
    }
}
